package com.Jian.reggie.controller;

import com.Jian.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * ClassName: CommonController
 * Package: com.Jian.reggie.controller
 * Description:
 *
 * @Description 文件上传和下载
 * @Author 蹇泽阳
 * @Create 2023/11/27 17:10
 * @Version 1.0
 */

@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController {
  @Value("${reggie.path}")
  private String basePath;
  
  @PostMapping("/upload")
  // 参数名要和前端发送的name一致  ！！！！
  public R<String> upload(MultipartFile file) {
    log.info("文件格式：" + file.toString());
    // 获取原始文件名
    String originalFilename = file.getOriginalFilename();
    // 截取文件后缀名
    String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
    // 使用UUID作为文件名，防止文件名重复
    String filename = java.util.UUID.randomUUID().toString() + suffix;
    // 将临时文件转存到指定位置（全局配置）
    File dir = new File(basePath);
    // 创建一个目录，判断目录是否存在
    if (!dir.exists()) {
      // 不存在则创建
      dir.mkdirs();
    }
    try {
      file.transferTo(new File(basePath + filename));
    } catch (IOException e) {
      e.printStackTrace();
    }
    
    return R.success(filename);
  }
  
  // 下载文件
  @GetMapping("/download")
  public void download(String name, HttpServletResponse response) {
    // 输入流，通过输入流读取文件内容
    try {
      FileInputStream fileInputStream = new FileInputStream(basePath + name);
      // 输出流，通过输出流将文件内容输出到浏览器
      ServletOutputStream outputStream = response.getOutputStream();
      response.setContentType("image/jpeg");
      
      byte[] buffer = new byte[1024];
      int len = 0;
      while ((len = fileInputStream.read(buffer)) != -1) {
        outputStream.write(buffer, 0, len);
        outputStream.flush();
      }
      // 关闭流
      fileInputStream.close();
      outputStream.close();
      
    } catch (Exception e) {
      throw new RuntimeException(e.getMessage());
    }
  }
}
